﻿# -*- coding: utf-8 -*-
'''eof
name:最近3个月贷款审批机构数与贷记卡审批查询次数
code:Mon3LoanCardQuerySum_2D
tableName:
columnName:
groups:个人征信
dependencies:IC_DSJ_2D
type:常用指标
dataSourceType:
eof'''
import re
import datetime
import sys
import json
import pandas as pd
import datetime
import traceback
reload(sys)
sys.setdefaultencoding('utf-8')

def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def getTable(data, tableName, occurTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :return:该表全部数据
        '''
    table = data.get(tableName)
    if occurTimes == 0:
        if table is None or table == "":
            return [{}]
        elif isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)
    if occurTimes == 1:
        if table == "":
            return [{}]
        elif table is None or isinstance(table, list) is False or len(table) == 0:
            return None
        elif len(table) == 0:
            return [{}]
        else:
            return data.get(tableName)


def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date


def IC8_Mon3LoanCardQuerySum():
    data = IC_DSJ_2D['data']
    returnList1 = []
    returnList2 = []
    null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']
    last_year_list = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset(months=i)).strftime('%Y%m%d') \
                          for i in [3, 0]]
    #try:
    table1=getTable(data,"POQ",1)
    if table1 is None:
        return u'缺失值'
    elif table1 == [{}]:
        return 0
    else:
        #查询记录信息单元
        PH01 = getTable(table1[0], 'PH01', 0)
        if table1 is None or table1==[{}]:
            return u"缺失值"
        if PH01 is None:
            return u'缺失值'
        elif PH01 == [{}]:
            return u'缺失值'
        else:
            for i in PH01:
                try:
                    #查询机构
                    PH010Q02=i.get('PH010Q02')
                    #查询日期
                    PH010R01=i.get('PH010R01')
                    queryDateFormat = Formate(PH010R01)
                    #查询原因
                    PH010Q03=i.get('PH010Q03')
                    if PH010Q02 in null_type_list or PH010R01 in null_type_list or PH010Q03 in null_type_list:
                        returnList1.append(None)
                        returnList2.append(None)
                    else:
                        if queryDateFormat>last_year_list[0] and queryDateFormat<=last_year_list[1] and PH010Q03 =="02":
                            returnList1.append(PH010Q02)
                        elif queryDateFormat>last_year_list[0] and queryDateFormat<=last_year_list[1] and PH010Q03 =="03":
                            returnList2.append(PH010Q02)
                        else:
                            returnList1.append(0)
                            returnList2.append(0)
                except:
                    returnList1.append(None)
                    returnList2.append(None)
            returnSet1=set(returnList1)
            returnSet2=set(returnList2)
            returnListNotNone1 = filter(lambda x:x  not in(None,0), returnSet1)
            returnListNotNone2 = filter(lambda x:x  not in (None,0), returnSet2)

            if len(returnListNotNone1) == 0 and len(returnListNotNone2) == 0:
                return u"缺失值"

            else:
                return len(returnListNotNone1)+len(returnListNotNone2)
    # except:
    #     return u"缺失值2"

result = IC8_Mon3LoanCardQuerySum()



